/*
 * @Description: 接收登记上下文
 * @Author: Rfan
 * @Date: 2022-11-23 18:05:57
 * @LastEditTime: 2022-11-23 18:29:24
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import {
  SET_REG_ACCESSION_LIST,
  DELETE_REGISTRATION_ITEM,
  SET_SELECTED_ITEM,
  ADD_REG_ACCESSION,
  EDIT_REG_ACCESSION
} from '../constants';
import { AccessionReducer } from '../reducers/AccessionReducer';
import { message, Modal } from 'antd';
import {
  addRegAccession,
  deleteRegAccessionItem,
  editRegAccession,
  fetchRegAccessionListByPage
} from '@/api/registration/accession';

const initialState = {
  // 选中的表格条目
  selectItems: [],

  list: [],

  // -------- 字典 --------
  // 检测结果列表
  resultsStatusList: [
    { id: 0, name: '成功' },
    { id: 1, name: '失败' }
  ],
  // 移交方式
  accessionTypeList: [
    { id: 1, name: '在线' },
    { id: 2, name: '离线' }
  ]
};

const AccessionContext = createContext();

const AccessionProvider = (props) => {
  const [state, dispatch] = useReducer(AccessionReducer, initialState);

  const actions = {
    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 获取接收登记列表
     * @param {IPageQuery<IRegAccessionListParams>} query
     * @return {*}
     */
    getRegAccessionList(query) {
      return new Promise((resolve, reject) => {
        fetchRegAccessionListByPage(query)
          .then((res) => {
            const { data } = res;
            console.log('pending', data);
            dispatch({
              type: SET_REG_ACCESSION_LIST,
              data: data.results
            });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 增加接收登记
     * @param {IAddRegAccessionParams} params
     * @return {any}
     */
    addRegAccessionFunc(params) {
      return new Promise((resolve, reject) => {
        addRegAccession(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_REG_ACCESSION, data, id: data.id });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 编辑移交登记
     * @param {IEditRegAccessionParams} params
     * @return {any}
     */
    editRegAccessionFunc(params) {
      return new Promise((resolve, reject) => {
        editRegAccession(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_REG_ACCESSION, data, id: data.id });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 删除登记条目
     * @param {number|number[]} id
     * @param {string} title
     */
    deleteItem(id, title = '是否移除选中的条目?') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteRegAccessionItem(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            message.success('删除成功');
            dispatch({ type: DELETE_REGISTRATION_ITEM, ids: data });
          });
        },
        onCancel() {
          console.log('del item Cancel');
        }
      });
    }
  };

  const filters = {
    resultFilter(id) {
      return state.resultsStatusList.find((item) => item.id === id)?.name || '-';
    },
    accessionTypeFilter(id) {
      return state.accessionTypeList.find((item) => item.id === id)?.name || '-';
    }
  };

  useEffect(() => {}, []);

  return (
    <AccessionContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </AccessionContext.Provider>
  );
};

export const useAccessionContext = () => {
  return useContext(AccessionContext);
};

export { AccessionContext, AccessionProvider };
